//
//  GJChooseDateView_new.m
//  YDGJ
//
//  Created by 黄卫 on 17/2/24.
//  Copyright © 2017年 huangwei. All rights reserved.
//

#import "GJChooseDateView_new.h"
#import "GJWindow.h"

@implementation GJDateButton_

- (void)setSelected:(BOOL)selected
{
    [super setSelected:selected];
    [self setDateStr:self.dateStr];
}

- (void)setDateStr:(NSString *)dateStr
{
    _dateStr = dateStr;
    NSString *curTitle = self.tag==10000?@"开始时间":@"结束时间";
    NSMutableAttributedString *mStr;
    if (dateStr.length==0) {
        mStr = [[NSMutableAttributedString alloc] initWithString:self.tag==10000?@"开始时间":@"结束时间"];
        if (self.isSelected) {
            [mStr setAttributes:@{NSFontAttributeName:FontCustomSize(14),NSForegroundColorAttributeName:Color_Main} range:NSMakeRange(0, 4)];
        }
        else
        {
            [mStr setAttributes:@{NSFontAttributeName:FontCustomSize(14),NSForegroundColorAttributeName:UIColorFromRGB(0xa4a4a4)} range:NSMakeRange(0, 4)];
        }
    }
    else
    {
        self.titleLabel.numberOfLines = 2;
        NSString *title = [curTitle stringByAppendingString:[@"\n" stringByAppendingString:dateStr]];
        mStr = [[NSMutableAttributedString alloc] initWithString:title];
        [mStr setAttributes:@{NSFontAttributeName:FontCustomSize(14),NSForegroundColorAttributeName:UIColorFromRGB(0xa4a4a4)} range:NSMakeRange(0, 4)];
        NSString *suffix = [title substringFromIndex:4];
        [mStr setAttributes:@{NSFontAttributeName:FontCustomSize(14),NSForegroundColorAttributeName:self.isSelected?Color_Main:UIColorFromRGB(0xa4a4a4)} range:[title rangeOfString:suffix options:NSBackwardsSearch]];
    }
    [self setAttributedTitle:mStr forState:UIControlStateNormal];
}

@end

#pragma mark ======================================新控件======================================

@interface GJChooseDateView_new ()

@property (nonatomic, copy) void (^block)(NSString *,NSString *);

@property (nonatomic, copy) NSString *startDate,*endDate;

@property (nonatomic, strong) UIWindow *bgWindow;

@property (nonatomic, strong) UIView *bgView;

@property (nonatomic, assign) DateChoosenViewStyle style;

@property (nonatomic, strong) UIDatePicker *datePicker;

@end

@implementation GJChooseDateView_new

#define EnsureBtn ((UIButton *)[_bgView viewWithTag:10001])
#define CancelBtn ((UIButton *)[_bgView viewWithTag:10000])
#define StartBtn ((GJDateButton_ *)[_bgView viewWithTag:20000])
#define EndBtn ((GJDateButton_ *)[_bgView viewWithTag:20001])

#pragma mark View相关

+ (void)showWithStyle:(DateChoosenViewStyle)style selectedBlock:(void (^)(NSString *,NSString *))blk
{
    [[[self alloc] initWithBlock:blk style:style] show];
}

- (instancetype)initWithBlock:(void (^)(NSString *,NSString *))blk style:(DateChoosenViewStyle)style
{
    if (self = [super init]) {
        self.block = blk;
        self.style = style;
        _bgView = [[UIView alloc] initWithFrame:CGRectMake(0, Screen_Height, Screen_Width, 44.5*(style>=0?2:1)+216)];
        _bgView.backgroundColor = [UIColor whiteColor];
        _bgView.userInteractionEnabled = YES;
        self.frame = [[UIScreen mainScreen] bounds];
        [self addSubview:_bgView];
        [self initSubViews];
    }
    return self;
}

- (instancetype)initWithBlock:(void (^)(NSString *,NSString *))blk style:(DateChoosenViewStyle)style startDate:(NSString *)startDate endDate:(NSString *)endDate
{
    if (self = [super init]) {
        self.block = blk;
        self.style = style;
        self.startDate = startDate;
        self.endDate = endDate;
        _bgView = [[UIView alloc] initWithFrame:CGRectMake(0, Screen_Height, Screen_Width, 44.5*(style>=0?2:1)+216)];
        _bgView.backgroundColor = [UIColor whiteColor];
        _bgView.userInteractionEnabled = YES;
        self.frame = [[UIScreen mainScreen] bounds];
        [self addSubview:_bgView];
        [self initSubViews];
    }
    return self;
}


+ (void)showWithStyle:(DateChoosenViewStyle)style startDate:(NSString *)startDate endDate:(NSString *)endDate selectedBlock:(void (^)(NSString *,NSString *))blk
{
    [[[self alloc] initWithBlock:blk style:style startDate:startDate endDate:endDate] show];
}

- (void)initSubViews
{
    for (int i = 0; i < 2; i++)
    {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn setTitle:i==0?@"取消":@"确定" forState:UIControlStateNormal];
        [_bgView addSubview:btn];
        btn.tag = 10000+i;
        if (i==0) {
            btn.center = CGPointMake(22, 22);
            btn.bounds = CGRectMake(0, 0, 44, 44);
            [btn setTitleColor:UIColorFromRGB(0x323232) forState:UIControlStateNormal];
            [btn setTitleColor:[UIColorFromRGB(0x323232) colorWithAlphaComponent:0.4] forState:UIControlStateHighlighted];
            [btn setTitleColor:[UIColorFromRGB(0x323232) colorWithAlphaComponent:0.1] forState:UIControlStateDisabled];
        }
        if (i==1) {
            btn.center = CGPointMake(Screen_Width-22, 22);
            btn.bounds = CGRectMake(0, 0, 44, 44);
            [btn setTitleColor:Color_Main forState:UIControlStateNormal];
            [btn setTitleColor:[Color_Main colorWithAlphaComponent:0.4] forState:UIControlStateHighlighted];
            [btn setTitleColor:Color_DisableBtn forState:UIControlStateDisabled];
            btn.enabled = NO;
        }
        [btn.titleLabel setFont:FontCustomSize(14)];
        [btn addTarget:self action:@selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];
        
        CGFloat width = _bgView.width/2.f-0.25;
        GJDateButton_ *btnDown = [GJDateButton_ buttonWithType:UIButtonTypeCustom];
        btnDown.titleLabel.numberOfLines = 0;
        [btnDown setBackgroundImage:imageWithColor(UIColorFromRGB(0xf5f5f5)) forState:UIControlStateSelected];
        [btnDown setBackgroundImage:nil forState:UIControlStateNormal];
        btnDown.titleLabel.textAlignment = NSTextAlignmentCenter;
        btnDown.frame = CGRectMake(i==0?0:width+0.5, _bgView.height-44, width, 44);
        btnDown.tag = 20000+i;
        btnDown.dateStr = nil;
        [_bgView addSubview:btnDown];
        [btnDown addTarget:self action:@selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    for (int i = 0; i < 4; i++) {
        UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, 44.5*i+44, Screen_Width, GJLineHeight)];
        line.backgroundColor = Color_Line;
        
        if (i==1||i==2) {
            
        }
        else
        {
            if (i==3) {
                line.y = _bgView.height-44.5;
            }
            [_bgView addSubview:line];
        }
    }
    UIView *line1 = [[UIView alloc] initWithFrame:CGRectMake(_bgView.width/2.f-0.25, _bgView.height-44, 0.5, 44)];
    line1.backgroundColor = Color_Line;
    [_bgView addSubview:line1];
    
    _datePicker = [[UIDatePicker alloc] init];
    _datePicker.datePickerMode = UIDatePickerModeDate;
    _datePicker.transform = CGAffineTransformScale(_datePicker.transform, 1.2, 1.2);
    _datePicker.y = 44.5;
    if (!self.startDate) {
        _datePicker.minimumDate = dateFromString(@"2010-01-01 08:00:00");
    }
    else {
        _datePicker.minimumDate = dateFromString([NSString stringWithFormat:@"%@ 08:00:00",self.startDate]);
    }
    if (!self.endDate) {
        _datePicker.maximumDate = [NSDate date];
    }
    else {
        _datePicker.maximumDate = dateFromString([NSString stringWithFormat:@"%@ 08:00:00",self.endDate]);
    }
    [self btnClicked:StartBtn];
    _datePicker.centerX = _bgView.centerX;
    NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];//设置为中
    _datePicker.locale = locale;
    [_bgView addSubview:_datePicker];
    
    [_datePicker addTarget:self action:@selector(pickerValueChanged:) forControlEvents:UIControlEventValueChanged];
    
    [self.bgWindow addSubview:self];
}

- (UIWindow *)bgWindow
{
    if (_bgWindow == nil) {
        _bgWindow = [[GJWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
        _bgWindow.windowLevel       = UIWindowLevelStatusBar;
        _bgWindow.backgroundColor   = [[UIColor blackColor] colorWithAlphaComponent:0];
        _bgWindow.hidden = NO;
        UITapGestureRecognizer *dismGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(dismiss:)];
        [_bgWindow addGestureRecognizer:dismGesture];
    }
    
    return _bgWindow;
}

#pragma mark 事件

- (void)btnClicked:(UIButton *)btn
{
    if (btn.tag == 10000) {
        [self dismiss:nil];
    }
    else if (btn.tag == 10001) {
        [self dismiss:nil];
        if (self.block) {
            self.block(_startDate,_endDate);
        }
    }
    else if (btn.tag == 20000) {
        StartBtn.selected = YES;
        EndBtn.selected = NO;
        if (!_startDate) {
            self.startDate = dateStringWithoutHMS([NSDate date]);
        }
    }
    else if (btn.tag == 20001) {
        StartBtn.selected = NO;
        EndBtn.selected = YES;
        if (!_endDate) {
            self.endDate = dateStringWithoutHMS([NSDate date]);
        }
    }
}

- (void)pickerValueChanged:(UIDatePicker *)picker
{
    if (StartBtn.isSelected) {
        self.startDate = dateStringWithoutHMS(picker.date);
    }
    else if (EndBtn.isSelected) {
        self.endDate = dateStringWithoutHMS(picker.date);
    }
}

#pragma mark 动画

- (void)show
{
    _bgWindow.hidden = NO;
    _bgWindow.backgroundColor   = [[UIColor blackColor] colorWithAlphaComponent:0];
    [UIView animateWithDuration:0.1f
                          delay:0
                        options:UIViewAnimationOptionCurveEaseOut
                     animations:^{
                         _bgWindow.backgroundColor   = [[UIColor blackColor] colorWithAlphaComponent:0.4];
                         CGRect frame = _bgView.frame;
                         frame.origin.y -= 44.5*2+216;
                         [_bgView setFrame:frame];
                         
                     }
                     completion:nil];
}

- (void)dismiss:(UIGestureRecognizer *)gesture {
    
    [UIView animateWithDuration:0.1f
                          delay:0
                        options:UIViewAnimationOptionCurveEaseOut
                     animations:^{
                         
                         _bgWindow.backgroundColor   = [[UIColor blackColor] colorWithAlphaComponent:0];
                         
                         CGRect frame = _bgView.frame;
                         frame.origin.y += 44.5*2+216;
                         [_bgView setFrame:frame];
                         
                     }
                     completion:^(BOOL finished) {
                         
                         _bgWindow.hidden = YES;
                         
                         [self removeFromSuperview];
                     }];
}

#pragma mark setter/getter

- (void)setStartDate:(NSString *)startDate
{
    _startDate = startDate;
    StartBtn.dateStr = _startDate;
    EnsureBtn.enabled = NO;
    if (_endDate&&_startDate&&[_endDate compare:_startDate]!=NSOrderedAscending) {
        EnsureBtn.enabled = YES;
    }
    else {
        if (!_endDate) {
            return;
        }
        [MBProgressHUD showError:@"结束时间需大于开始时间" toView:_bgWindow model:NO];
    }
}

- (void)setEndDate:(NSString *)endDate
{
    _endDate = endDate;
    EndBtn.dateStr = _endDate;
    EnsureBtn.enabled = NO;
    if (_endDate&&_startDate&&[_endDate compare:_startDate]!=NSOrderedAscending) {
        EnsureBtn.enabled = YES;
    }
    else {
        if (!_endDate) {
            return;
        }
        [MBProgressHUD showError:@"结束时间需大于开始时间" toView:_bgWindow model:NO];
    }
}

@end
